package com.cloudservice.ccs.biz.impl;

import com.cloudservice.ccs.biz.ILoginBiz;
import com.cloudservice.ccs.entity.CustomerService;
import com.cloudservice.ccs.model.LoginData;
import com.cloudservice.ccs.mapper.CustomerServiceMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginImpl implements ILoginBiz {
    @Autowired
    private CustomerServiceMapper customerServiceMapper;

    @Override
    public CustomerService doLogin(LoginData loginData) {
        String email = loginData.getEmail(), password = loginData.getPassword();
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(email,password);
        subject.login(token);
        Map<String, Object> conditions = new HashMap<>(1);
        conditions.put("email", email);
        CustomerService foundCustomerService = customerServiceMapper.getWithConditions(conditions).get(0);
        foundCustomerService.setState("在线");
        customerServiceMapper.update(foundCustomerService.getCustomerServiceId(), foundCustomerService);
        return foundCustomerService;
    }

    @Override
    public void doLogout() {
        Subject subject = SecurityUtils.getSubject();
        Integer customerServiceId = (Integer) subject.getPrincipal();
        subject.logout();
        Map<String, Object> updatedItems = new HashMap<>(1);
        updatedItems.put("state", "离线");
        customerServiceMapper.partialUpdate(customerServiceId, updatedItems);
    }
}
